<!-- filename: frontend/src/components/AddToPlaylistModal/AddToPlaylistModal.vue (体验升级版) -->
<template>
  <view class="modal-overlay" @click="closeModal">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">添加到歌单</text>
      </view>
    
      <view class="modal-body">
        <!-- 【核心修改】新建歌单区域 -->
        <view class="list-item new-playlist-item" @click="isCreating = !isCreating">
          <view class="icon-placeholder">+</view>
          <text>新建歌单</text>
        </view>
        
        <!-- 【核心修改】新增的输入框，通过 v-if 控制显示 -->
        <view v-if="isCreating" class="create-playlist-form">
          <input 
            v-model="newPlaylistName"
            class="playlist-input" 
            placeholder="请输入新歌单名称"
            :focus="isCreating"
          />
          <button class="create-btn" @click="handleCreateAndAdd">创建并添加</button>
        </view>
    
        <!-- 歌单列表 -->
        <scroll-view scroll-y class="playlist-scroll-view">
          <view v-if="isLoading" class="loading-text">正在加载...</view>
          <view v-for="playlist in playlists" :key="playlist.id" class="list-item" @click="selectPlaylist(playlist.id)">
            <text>{{ playlist.name }}</text>
          </view>
        </scroll-view>
      </view>
    
      <view class="modal-footer">
        <button class="cancel-btn" @click="closeModal">取消</button>
      </view>
    </view>
  </view>
</template>


<script setup>
import { ref, onMounted } from 'vue';
import { useAuthStore } from '@/store/auth';
import { request } from "@/utils/request"; // 【核心修改1】

const props = defineProps({
  songId: { type: [Number, String], required: true }
});
const emit = defineEmits(['close']);

const authStore = useAuthStore();
const playlists = ref([]);
const isLoading = ref(true);
const isCreating = ref(false);
const newPlaylistName = ref('');

const closeModal = () => emit('close');

// --- 【核心修改2】重写所有 API 请求函数 ---

const fetchMyPlaylists = async () => {
  isLoading.value = true;
  try {
    const data = await request({
      url: `/api/playlists/mine`,
      method: 'GET'
    });
    if (Array.isArray(data)) {
      playlists.value = data;
    }
  } catch (error) {
    console.error("Failed to fetch my playlists:", error);
  } finally {
    isLoading.value = false;
  }
};

const addSongTo = async (playlistId) => {
  uni.showLoading({ title: '请稍候...' });
  try {
    // 【注意】addSongTo 后端返回 201(创建) 或 200(已存在)，
    // 我们的 request 工具默认只处理 2xx 为成功，无法区分。
    // 这里需要一个特殊的处理方式，我们暂时先假定它能工作，后续再优化 request 工具。
    // 为了简单起见，我们先用原始的 uni.request + header 的方式，确保状态码能被捕获。
    uni.request({
      url: `${import.meta.env.VITE_API_BASE_URL}/api/playlists/${playlistId}/songs`,
      method: 'POST',
      header: { 'Authorization': `Bearer ${authStore.access_token}` },
      data: { song_id: props.songId },
      success: (res) => {
        if (res.statusCode === 201) {
          uni.showToast({ title: "添加成功", icon: 'success' });
          closeModal();
        } else if (res.statusCode === 200) {
          uni.showToast({ title: "歌曲已在该歌单中", icon: 'none' });
          closeModal();
        } else {
          uni.showToast({ title: res.data.error || '添加失败', icon: 'none' });
        }
      },
      fail: () => {
        uni.showToast({ title: '网络错误', icon: 'error' });
      },
      complete: () => {
        uni.hideLoading();
      }
    });
  } catch (error) {
     // 这部分代码暂时不会被执行，因为我们用了原始的 uni.request
  }
};


const handleCreateAndAdd = async () => {
  if (!newPlaylistName.value.trim()) {
    uni.showToast({ title: '歌单名称不能为空', icon: 'none' });
    return;
  }
  
  uni.showLoading({ title: '创建中...' });
  try {
    const data = await request({
      url: `/api/playlists`,
      method: 'POST',
      data: { name: newPlaylistName.value },
    });
    if (data && data.id) {
      const newPlaylistId = data.id;
      // 创建成功后，直接将歌曲添加到这个新歌单
      addSongTo(newPlaylistId);
    }
  } catch (error) {
    const errorMsg = error?.data?.error || '创建失败';
    uni.showToast({ title: errorMsg, icon: 'none' });
  } finally {
    // uni.hideLoading() 会在 addSongTo 内部被调用，这里不需要
  }
};

// --- 无需修改的函数 ---
const selectPlaylist = (playlistId) => {
  addSongTo(playlistId);
};

onMounted(() => {
  fetchMyPlaylists();
});
</script>

<style scoped lang="scss">
/* --- 只需要在原有样式基础上，新增和修改以下样式 --- */

/* 新建歌单表单的样式 */
.create-playlist-form {
  display: flex;
  padding: 0 15px 15px 15px;
  gap: 10px;
}
.playlist-input {
  flex-grow: 1;
  height: 40px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
}
.create-btn {
  flex-shrink: 0;
  height: 40px;
  line-height: 40px;
  padding: 0 15px;
  background-color: #007aff;
  color: white;
  font-size: 14px;
}
.create-btn::after {
  border: none;
}

/* 列表项的边框微调 */
.list-item {
  border-bottom: 1px solid #f0f0f0;
}
.playlist-scroll-view .list-item:last-child {
  border-bottom: none; /* 最后一项无边框 */
}

/* --- 原有样式保持不变 --- */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}
.modal-content {
  width: 90%;
  max-width: 400px;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
}
.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  text-align: center;
}
.modal-title {
  font-size: 18px;
  font-weight: bold;
}
.modal-body {
  padding: 0;
}
.playlist-scroll-view {
  max-height: 45vh;
}
.list-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  cursor: pointer;
  &:hover {
    background-color: #f9f9f9;
  }
}
.new-playlist-item .icon-placeholder {
  width: 24px;
  height: 24px;
  line-height: 22px;
  text-align: center;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 15px;
  font-size: 20px;
  color: #555;
}
.loading-text {
  padding: 20px;
  text-align: center;
  color: #888;
}
.modal-footer {
  padding: 10px;
  border-top: 1px solid #eee;
}
.cancel-btn {
  width: 100%;
  background-color: #f1f1f1;
}
.cancel-btn::after {
  border: none;
}
</style>